/*
 * This api js IS NOT the apicloud api.js, DO NOT mess up!!!
 * Promisify the apicloud API ajax function, nice to use
 */

function ajax({ method = 'get', url, headers, data, report = false }) {
    return new Promise((resolve, reject) => {
        api.ajax({ url, method, headers, data, report }, (ret, err) => {
            if (err) {
                reject(err)
            }
            if (ret.status !== undefined && ret.status !== 200) {
                reject(ret.msg)
            }

            resolve(ret)
        })
    })
}

const url = 'http://47.104.159.220:8088';
// const url = 'http://172.16.100.204:8088';
export const API = {
    async login(username, password) {
        const config = {
            'method': 'post',
            'url': url+'/login',
            'data': {
                'values': {
                    'username': username,
                    'password': password
                }
            }
        };
        return await ajax(config)
    },
    async realnames(username, page=1) {
        const config = {
            'method': 'post',
            'url': url+'/realnames',
            'data': {
                'values': {'username': username, 'page': page}
            }
        };
        return await ajax(config)
    },
    async realname_count(username) {
        const config = {
            'method': 'post',
            'url': url+'/count/realname',
            'data': {
                'values': {'username': username}
            }
        };
        return await ajax(config)
    },
    async uploadRealname(username, realname, audio_file) {
        const config = {
            'method': 'post',
            'url': url+'/upload/realname',
            'data': {
                'values': {
                    'username': username,
                    'realname': realname
                },
                'files': {
                    'file': audio_file
                }
            }
        };
        return await ajax(config)
    },
    async scripts(username) {
        const config = {
            'method': 'post',
            'url': url+'/scripts',
            'data': {
                'values': {'username': username}
            }
        };
        return await ajax(config)
    },
    async script_count(username) {
        const config = {
            'method': 'post',
            'url': url+'/count/script',
            'data': {
                'values': {'username': username}
            }
        };
        return await ajax(config)
    },
    async uploadScript(username, script_id, audio_file) {
        const config = {
            'method': 'post',
            'url': url+'/upload/script',
            'data': {
                'values': {
                    'username': username,
                    'script_id': script_id
                },
                'files': {
                    'file': audio_file
                }
            }
        };
        return await ajax(config)
    },
}
